﻿Public Class TiledBackground
    Inherits GameBackground

    Private _MapTileIndicies(,) As Integer
    Private _MapSize As Size
    Public Property MapSize As Size
        Get
            Return _MapSize
        End Get
        Set(value As Size)
            _MapSize = value
            ReDim Preserve _MapTileIndicies(_MapSize.Width - 1, _MapSize.Height - 1)
        End Set
    End Property

    Public Property TileSize As Size

    Private _Tiles As New TiledBackgroundTileCollection
    Public ReadOnly Property Tiles As TiledBackgroundTileCollection
        Get
            Return _Tiles
        End Get
    End Property

    Public Property ViewPortPosition As Point

    Public Function GetMapTile(mapPosition As Point) As TiledBackgroundTile
        Return _Tiles(_MapTileIndicies(mapPosition.X, mapPosition.Y))
    End Function

    Public Function GetObjectMapTilePosition(target As GameObject) As Point
        Dim deltaX As Integer = CInt(Math.Floor(target.Position.X / TileSize.Width))
        Dim deltaY As Integer = CInt(Math.Floor(target.Position.Y / TileSize.Height))
        Return New Point(ViewPortPosition.X + deltaX, ViewPortPosition.Y + deltaY)
    End Function

    Public Function GetTileUnderObject(target As GameObject) As TiledBackgroundTile
        Return GetMapTile(GetObjectMapTilePosition(target))
    End Function

    Protected Friend Overrides Sub OnDraw(e As DrawEventArgs)
        MyBase.OnDraw(e)

        Dim xDelta As Integer = ViewPortPosition.X * TileSize.Width
        Dim yDelta As Integer = ViewPortPosition.Y * TileSize.Height
        Dim widthDelta As Integer = CInt(Math.Ceiling(e.Engine.Canvas.ClientSize.Width / TileSize.Width))
        Dim heightDelta As Integer = CInt(Math.Ceiling(e.Engine.Canvas.ClientSize.Height / TileSize.Height))
        For x As Integer = xDelta To xDelta + widthDelta - 1
            For y As Integer = yDelta To yDelta + heightDelta - 1
                _Tiles(_MapTileIndicies(x, y)).OnDraw(e, x, y)
            Next
        Next
    End Sub

End Class





